package com.asd.common.interceptors;

import com.alibaba.fastjson.JSON;
import com.asd.common.annotation.Aspect;
import com.asd.common.annotation.RequestBody;
import com.asd.common.annotation.RequestParam;
import com.asd.common.interceptors.bean.InvocationBean;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @author zhanqi
 * @since 2022/5/6 23:58
 */
@Aspect(3)
public class RequestBodyAspect extends BaseAspect {
    @Override
    public boolean exe(InvocationBean inv) {
        Method method = inv.getMethod();
        HttpServletRequest req = inv.getReq();
        String bodyStr = inv.getBodyStr();
        Parameter[] parameters = method.getParameters();
        if (parameters.length < 1) {
            return true;
        }
        Object[] methodParameters = new Object[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null && bodyStr != null) {
                Class<?> aClass = parameters[i].getType();
                Object bean;
                if (JSON.isValid(bodyStr)) {
                    bean = JSON.parseObject(bodyStr, aClass);
                } else {
                    try {
                        bean = inv.getCt().convertToObj(bodyStr, aClass);
                    } catch (JAXBException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                methodParameters[i] = bean;
            }
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                String val = req.getParameter(requestParam.value());
                methodParameters[i] = val;
            }
        }
        inv.setMethodParameters(methodParameters);
        return true;
    }
}
